package org.webby.security;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Processes the auth cookie and puts the authenticated ID (if any) into a request attribute
 */
public class AuthFilter implements Filter {
  private WebAuthService webAuthService;

  public void init(FilterConfig filterConfig) throws ServletException {
    webAuthService = (WebAuthService) filterConfig.getServletContext().getAttribute(WebAuthService.CTX_ATTR_NAME);
    if (webAuthService == null) {
      throw new ServletException("missing required servlet context attribute " + WebAuthService.CTX_ATTR_NAME);
    }
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
      webAuthService.authenticate((HttpServletRequest) request, (HttpServletResponse) response);
    }
    chain.doFilter(request, response);
  }

  public void destroy() {
  }
}
